package com.mi.cmdtest;


import android.app.Activity;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
import android.widget.TextView;

import com.magilit.framelibrary.annotations.ViewInject;
import com.magilit.framelibrary.base.FrameNormalActivity;
import com.magilit.framelibrary.dialog.SweetAlertDialog;
import com.magilit.framelibrary.utils.ToastUtils;
import com.mi.cmdlibrary.magilit.bt.MagilitBT;
import com.mi.cmdlibrary.magilit.callback.MagilitDeviceSearchCallback;
import com.mi.cmdlibrary.magilit.callback.OnMagilitDeviceListener;
import com.mi.cmdlibrary.utils.MagilitBTHelper;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 */
public class SearchDeviceActivity extends FrameNormalActivity implements DevicesSearchedAdapter.OnDeviceClickListener, View.OnClickListener, OnMagilitDeviceListener {
    //搜索到的设备
    private RecyclerView recyclerView_devices;
    private List<DeviceSearch> data = new ArrayList<>();
    private DevicesSearchedAdapter adapter;
    //搜索弹出
    private SweetAlertDialog dialog;
    //动画
    private RotateAnimation animation;

    //提示信息
    @ViewInject(R.id.tv_search_message)
    private TextView tv_search_message;
    //头部提示信息
    @ViewInject(R.id.tv_search_message_top)
    private TextView tv_search_message_top;

    //测试
    @ViewInject(R.id.tv_test)
    private TextView tv_test;

    //扫描按键
    @ViewInject(R.id.iv_search_update)
    private ImageView iv_search_update;
    private MagilitDeviceSearchCallback callback;

    private MagilitBT bt;

    @Override
    protected void onBaseActivityCreated(Bundle savedInstanceState) {
        setMyContentView(R.layout.activity_search_device2);
        changeMessageByState(1);
        iv_search_update.setOnClickListener(this);
        tv_test.setOnClickListener(this);
        bt = TestApplication.getInstance().getBt1();
        bt.addOnMagilitDeviceListener(this);
    }

    private void startAnimation() {
        animation = new RotateAnimation(0f, 360f, Animation.RELATIVE_TO_SELF,
                0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        animation.setDuration(1000);//设置动画持续时间
        animation.setFillAfter(true);
        animation.setRepeatCount(Animation.INFINITE);
        iv_search_update.clearAnimation();
        iv_search_update.setAnimation(animation);
        animation.startNow();
    }

    private void initCallback() {

        callback = new MagilitDeviceSearchCallback() {
            Comparator<DeviceSearch> comparator = new Comparator<DeviceSearch>() {
                @Override
                public int compare(DeviceSearch d1, DeviceSearch d2) {
                    int s1 = d1.getRssi();
                    int s2 = d2.getRssi();
                    if (s1 < s2) {
                        return 1;
                    } else if (s2 == s1) {
                        return 0;
                    } else {
                        return -1;
                    }
                }
            };

            @Override
            public void onDeviceSearched(BluetoothDevice device, int rssi, String name) {
                DeviceSearch deviceSearch = new DeviceSearch();
                deviceSearch.setBle_name(name);
                deviceSearch.setBluetoothDevice(device);
                deviceSearch.setRssi(rssi);
                data.add(deviceSearch);
                Collections.sort(data, comparator);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        adapter.notifyDataSetChanged();
                    }
                });
            }
        };


        MagilitBTHelper.getInstance().setScanCallback(callback);
    }

    private void stopAnimation() {
        iv_search_update.clearAnimation();
    }


    /**
     * 弹出蓝牙扫描对话框
     */
    private void showSweetDialog() {
        data.clear();
        View view = getLayoutInflater().inflate(R.layout.dialog_devices, null);
        recyclerView_devices = (RecyclerView) view.findViewById(R.id.recyclerView_dialog_search);
        adapter = new DevicesSearchedAdapter(this, data);
        LinearLayoutManager manager2 = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        recyclerView_devices.setAdapter(adapter);
        recyclerView_devices.setLayoutManager(manager2);
        dialog = new SweetAlertDialog(this);
        dialog.setTitleText("选择设备");
        dialog.show();
        dialog.setCanceledOnTouchOutside(false);
        dialog.setCancelText("取消");
        dialog.setCustomView(view);
        dialog.setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
            @Override
            public void onClick(SweetAlertDialog sweetAlertDialog) {
                MagilitBTHelper.getInstance().stopScan();
                stopAnimation();
                sweetAlertDialog.dismiss();
                changeMessageByState(1);
            }
        });
        dialog.setConfirmText("确认");
        dialog.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
            @Override
            public void onClick(SweetAlertDialog sweetAlertDialog) {
                boolean hasSelected = false;
                for (DeviceSearch deviceSearch : data
                        ) {
                    if (deviceSearch.isSelected()) {
                        hasSelected = true;
                        device = deviceSearch;
                        MagilitBTHelper.getInstance().stopScan();
                        sweetAlertDialog.dismiss();
                        stopAnimation();
                        rentCheck();
                        break;
                    }
                }
                if (!hasSelected) {
                    ToastUtils.show(SearchDeviceActivity.this, "请选择需要连接的设备");
                }
            }
        });
        adapter.setOnDeviceClickListener(this);
    }

    /**
     * 蓝牙开启
     */
    private void openBLE() {
        if (MagilitBTHelper.getInstance().checkHasBle()) {
            showSweetDialog();
            MagilitBTHelper.getInstance().startDialogScan();
        } else {
            MagilitBTHelper.getInstance().openBle(this, 111);
        }
    }

    @Override
    public void onDeviceClick(DeviceSearch device) {
        for (DeviceSearch deviceSearch : data
                ) {
            deviceSearch.setSelected(false);
        }
        device.setSelected(true);
        adapter.notifyDataSetChanged();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 111) {
            switch (resultCode) {
                case Activity.RESULT_OK:
                    showSweetDialog();
                    MagilitBTHelper.getInstance().startDialogScan();
                    break;
                case Activity.RESULT_CANCELED:
                    break;
                default:
                    break;
            }
        }
    }


    @Override
    protected void onDestroy() {
        MagilitBTHelper.getInstance().stopScan();
        TestApplication.getInstance().getBt1().removeMagilitDeviceListener(this);
        super.onDestroy();
    }

    @Override
    protected boolean showToolBar() {
        return false;
    }


    DeviceSearch device;
    private boolean waitConnect;

    /**
     * 请求连接蓝牙
     */
    private void startConnect(DeviceSearch deviceSearch) {
        if (deviceSearch != null) {
            waitConnect = true;
            bt.setBluetoothDevice(deviceSearch.getBluetoothDevice());
            bt.connect();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_search_update:
                //文字提示
                bt.disconnect();
                changeMessageByState(2);
                startAnimation();
                initCallback();
                openBLE();
                break;

        }
    }

    /**
     * 根据状态显示不同UI
     *
     * @param state 1：普通状态，等待扫描
     *              2:正在搜索
     *              3:正在尝试连接蓝牙物理层
     *              4:发送配对指令，等待返回
     */
    private void changeMessageByState(final int state) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                switch (state) {
                    case 1:
                        tv_search_message.setTextColor(Color.BLACK);
                        tv_search_message.setText("点击右侧开始搜索");
                        tv_search_message_top.setText("    请确保设备与手机靠近、设备处于开启状态\n确认无误后点击右下角搜索键");
                        break;
                    case 2:
                        tv_search_message.setTextColor(Color.BLACK);
                        tv_search_message.setText("正在寻找设备中");
                        break;
                    case 3:
                        tv_search_message.setTextColor(Color.BLACK);
                        tv_search_message.setText("正在尝试连接...");
                        tv_search_message_top.setText("等待连接，如长时间未响应请重新连接");
                        break;
                    case 4:
                        tv_search_message.setTextColor(Color.RED);
                        tv_search_message.setText("请按设备确认键3~4秒完成连接");
                        tv_search_message_top.setText("");
                        break;
                }

            }
        });
    }

    private void rentCheck() {
        startConnect(device);
        changeMessageByState(3);
    }

    @Override
    public void onConnectFail(String tag) {
        //连接失败\
        if (waitConnect) {
            bt.reconnect();
        }
    }

    @Override
    public void onDisconnect(String tag) {
        //监听到断开
    }

    @Override
    public void onPairSuccess(String tag, String key) {
        //配对成功
        finish();
    }

    @Override
    public void onNoKeySend(String tag) {
        //请求设备返回指令
        changeMessageByState(4);
    }

    @Override
    public void onReconnect(String tag) {
        //重连中
    }
}
